#include "lienSerieMC.h"

void initialisationUSART (unsigned char port)
{
    if (port == 1)
    {
        USART_RX1_AN = PIN_NUMERIQUE;
        USART_TX1_AN = PIN_NUMERIQUE;
        USART_RX1_DIR = PIN_ENTREE;
        USART_TX1_DIR = PIN_ENTREE;

        Open1USART(USART_TX_INT_OFF&
                   USART_RX_INT_OFF&
                   USART_ASYNCH_MODE&
                   USART_EIGHT_BIT&
                   USART_CONT_RX&
                   USART_BRGH_HIGH,
                   SPRGB_9600);
    }
    #ifdef __18LF25K22
    else if (port == 2)
    {
        
        USART_RX2_DIR = PIN_ENTREE;
        USART_TX2_DIR = PIN_ENTREE;

        Open2USART(USART_TX_INT_OFF&
                   USART_RX_INT_OFF&
                   USART_ASYNCH_MODE&
                   USART_EIGHT_BIT&
                   USART_CONT_RX&
                   USART_BRGH_HIGH,
                   SPRGB_9600);
        
    }
    #endif
}

//void emission(unsigned char port, char *donnee, unsigned char taille)
void emission(unsigned char port, char donnee)
{
//    int i=0;
    if (port == 1)
    {
//        for (i=0; i<taille; i++)
//        {
//            Write1USART(donnee[i]);
//            while (Busy1USART());
//        }
        while (Busy1USART());
        Write1USART(donnee);
    }
    #ifdef __18LF25K22
    else if (port == 2)
    {
//        for (i=0; i<taille; i++)
//        {
//            Write2USART(donnee[i]);
//            while (Busy2USART());
//        }
        while (Busy2USART());
        Write2USART(donnee);
    }
    #endif
}

char reception (unsigned char port, char *donnee, unsigned int timeOut)
{
    setWatchDog(timeOut,WD_LIEN_SERIE);
    if (port == 1)
    {
        while (checkWatchDog(WD_LIEN_SERIE) == FAUX)
        {
            if (OverrunErrorUSART1)
                ResetUSART1 = 0;

            if (DataRdy1USART())
            {
                *donnee = Read1USART();
                return CAR_RECU;
            }
        }       
    }
    #ifdef __18LF25K22
    else if (port == 2 )
    {
        while (checkWatchDog(WD_LIEN_SERIE) == FAUX)
        {
            if (OverrunErrorUSART2)
                ResetUSART2 = 0;

            if (DataRdy2USART())
            {
                *donnee = Read2USART();
                return CAR_RECU;
            }
        }
    }
    #endif
    return TIMEOUT_WTD;
}
